import org.omg.CORBA.Request;

import javax.xml.ws.Response;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class Transport {


    public static void main(String[] args) throws IOException {
        Transport transport =new Transport();
        String text="你好";
        String texts=transport.transport(text,"en");
        System.out.println(texts);

    }
//    private static final OkHttpClient client = new OkHttpClient();
    // 接收需要转化的数据和转化的语言
    public String transport(String text, String targetLang) throws IOException {
//        // 目标URL
        String urlString = "https://findmyip.net/api/translate.php?text="+text+"&target_lang="+targetLang;

//        // 创建URL对象
        URL url = new URL(urlString);

        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为GET
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0");

        // 获取响应码，200表示成功
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析JSON响应以提取translate_result
            String json = response.toString();
            // 这里简单地用substring处理响应字符串，实际应用中建议使用JSON解析库如Jackson或Gson
            int startIndex = json.indexOf("\"translate_result\":\"") + "\"translate_result\":\"".length();
            int endIndex = json.indexOf("\"", startIndex);
            String translateResult = json.substring(startIndex, endIndex);

//            System.out.println("translate_result: " + translateResult);
            // 关闭连接
            connection.disconnect();
            return translateResult;
        } else {
            System.out.println("请求失败，响应码: " + responseCode);
            connection.disconnect();
            return null;
        }


//        Request request = new Request.builder()
//                .url("https://www.example.com")
//                .build();
//        try (Response response = client.newCall(request).execute()) {
//            String result = response.body().string();
//            System.out.println(result);
//            return result;
//        }
        

    }
}